package com.xiaoma.tpo.dao;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.xiaoma.tpo.baseDao.BaseDaoImpl;
import com.xiaoma.tpo.baseDao.DefaultRowMapper;
import com.xiaoma.tpo.domain.ForumPost;
import com.xiaoma.tpo.dto.ForumPostRaw;
import com.xiaoma.tpo.utils.Pager;

@Repository
public class ForumPostDao extends BaseDaoImpl<ForumPost>{

private static final Logger LOG = LoggerFactory.getLogger(ForumPostDao.class);
    
    public Pager find1Posts(Integer topicId,int startIndex, int itemsPerPage) {
        Pager pager = new Pager();
        Object[] params = new Object[]{topicId, startIndex, itemsPerPage};
        String sql = "SELECT a.id, IFNULL(b.nickname,b.name) user_name, b.avatar, a.topic_id, a.parent_id, a.content, a.created_at, a.owner, a.imgs FROM forum_post a left join user b on a.user_id = b.id where a.topic_id = ? and a.parent_id = 0 order by a.id desc limit ?,?";
        String sqlCount = "SELECT count(1) from forum_post where topic_id = ? and parent_id = 0";
        
        LOG.info(sql + " PARAMS: "  + topicId + ","+ startIndex + ", " + itemsPerPage);
        LOG.info(sqlCount);
        List<?> list = jdbcTemplate.query(sql, params, new DefaultRowMapper(ForumPostRaw.class, getNameHandler()));
        int totalCount = jdbcTemplate.queryForInt(sqlCount, topicId);
        pager.setList(list);
        pager.setTotalCount(totalCount);
        return pager;
    }
    public Pager find2Posts(Integer parentId,int startIndex, int itemsPerPage) {
        Pager pager = new Pager();
        Object[] params = new Object[]{ parentId, startIndex, itemsPerPage};
        String sql = "SELECT a.id, IFNULL(b.nickname,b.name) user_name, b.avatar, a.topic_id, a.parent_id, a.content, a.created_at, a.owner, a.imgs FROM forum_post a left join user b on a.user_id = b.id where a.parent_id = ? order by a.id desc limit ?,? ";
        String sqlCount = "SELECT count(1) from forum_post where parent_id = ?";
        
        LOG.info("SQL:{};  parentId:{}; startIndex:{}; itemsPerPage:{}",sql, parentId, startIndex, itemsPerPage);
        LOG.info(sqlCount);
        List<?> list = jdbcTemplate.query(sql, params, new DefaultRowMapper(ForumPostRaw.class, getNameHandler()));
        int totalCount = jdbcTemplate.queryForInt(sqlCount, parentId);
        pager.setList(list);
        pager.setTotalCount(totalCount);
        return pager;
    }
}
